<template>
    <div class="PostBuild">
        <div style="height:20px;"></div>
        <!-- 两端对齐 -->
        <van-row type="flex" justify="space-between">
            <van-col span="12" style="padding-left:5px;">
                <van-button square type="danger" style="float:left;" size="normal" @click="clickCancel">取消</van-button>
            </van-col>
            <van-col span="12" style="padding-right:5px;">
                <van-button square type="primary" style="float:right;" size="normal" @click="clickPost">发布</van-button>
            </van-col>
        </van-row>

        <van-dialog v-model="show_dialog" :title="dialog_title" :show-confirm-button="show_dialog" :show-cancel-button="show_dialog" @confirm="onConfirm" @cancel="onCancel">
            <Adsense data-ad-client="ca-pub-6243451787655828" data-ad-slot="4209566881">
            </Adsense>
        </van-dialog>

        <div style="height:20px;"></div>
        <van-field v-model="message" rows="5" autosize type="textarea" placeholder="创建私人配置清单，说点什么吧～（焊接心得、装机过程、踩坑经历、调参技巧...）" />
        <div style="height:20px;"></div>
        <van-uploader v-model="imageList" :max-count="12" preview-size="100px" :afterRead="afterRead" :beforeRead="beforeRead" />
        <div style="height:20px;"></div>
        <van-cell is-link @click="showPopup">添加零件
            <van-badge :content="choosePartList.length" />
        </van-cell>


        <van-empty v-if="choosePartList.length==0" description="暂无零件" />
        <van-swipe-cell v-for="item in choosePartList" :key="item.id" :before-close="beforeClose" :name="item.id" style="margin-top:0;">
            <van-card :desc="item.name" :thumb="item.img">
                <template #tags>
                    <van-tag plain type="danger" style="text-align:left;">{{item.part_name}}</van-tag>
                </template>
            </van-card>
            <template #right>
                <van-button square text="删除" type="danger" class="delete-button" />
            </template>

        </van-swipe-cell>
        <InFeedAdsense data-ad-layout-key="-gw-3+1f-3d+2z" data-ad-client="ca-pub-6243451787655828" data-ad-slot="8442301843">
        </InFeedAdsense>
        <van-popup v-model="show" closeable position="bottom" :style="{ height: '90%' }" overlay-class="myclass" duration="0.4" @open="openPartListPopup">

            <van-row>
                <van-col span="6">


                    <van-sidebar v-model="activeKey" @change="onChange">
                        <van-sidebar-item v-for="pt in partsType" :key="pt.id" :title="pt.name" />
                        <div :style="popup_blank_box_style"></div>
                    </van-sidebar>
                </van-col>
                <van-col span="18" class="search">
                    <van-search v-model="value" placeholder="请输入搜索关键词" class="search-bar" :clearable=false @input="onInput" />
                    <van-list v-model="loading" :finished="finished" @load="onLoad">
                        <van-card v-for="pl in partsList" @click="choosePart(pl.id,pl.name,pl.img,current_partName)" :key="pl.id" :desc="pl.name" :thumb="pl.img" />
                        <InFeedAdsense data-ad-layout-key="-gw-3+1f-3d+2z" data-ad-client="ca-pub-6243451787655828" data-ad-slot="8442301843">
                        </InFeedAdsense>



                        <div v-if="finished" style="padding-bottom: 30px;">
                          <p style="font-size:12px;text-align:center;color:grey;line-height:35px;">到底了👻如果找不到想要的零件👇</p>
                          <van-button color="#f60" url="https://www.17fpv.com/723.html" style="margin: auto;display: block;" size="small">向小哥反馈</van-button>
                        </div>


                    </van-list>
                    <div :style="popup_blank_box_style"></div>
                </van-col>

            </van-row>

        </van-popup>
    </div>
</template>

<script>
    import 'vant/lib/index.css';
    import lrz from "lrz";

    export default
    {
        name: 'PostBuild',
        props:
        {

        },
        components:
        {

        },
        created()
        {
            let height = window.outerHeight
            this.popup_blank_box_style = 'height:' + (height * 0.1) + 'px';

        },
        data()
        {
            return {
                show: false,
                activeKey: 0,
                value: '',
                loading: false,
                finished: false,
                refreshing: false,
                partsType: [],
                partsList: [],
                choosePartList: [],
                imageList: [],
                message: '',
                current_start: 0,
                current_type: 1,
                current_partName: '机架',
                cancelRequest: null,
                popup_blank_box_style: '', //popup补位box高度
                show_dialog: false, //是否展示弹框
                toast_post: null, //发布文章的toast提示
                dialog_title: '',
            };
        },

        methods:
        {
            showPopup()
            {
                this.show = true;
            },
            onLoad()
            {

                //此方法来源有几种：1，正常下拉加载 2，切换tab栏 3，搜索关键词
                //1，正常下拉加载(需要等到之前所有的内容加载完毕之后才能继续加载)
                //2，切换tab栏目（直接清除之前的axios请求，加载新内容）
                //3，搜索关键词（直接清除之前的axios请求，加载新内容）

                //判断逻辑：如果current_start >= 1，则认为是正常下拉加载
                if (this.current_start >= 1)
                {
                    // console.log(this.current_start)
                    // if (this.loading) {
                    //   return
                    // }
                }
                // 如果current_start = 0，则认为是需要撤销之前的请求
                if (this.current_start == 0)
                {

                    // 2. 准备执行新的请求前，先将前一个请求取消
                    // 如果前一个请求执行完了，执行取消请求不会有其他操作
                    if (typeof(this.cancelRequest) === 'function')
                    {
                        this.cancelRequest("请求太频繁了，请稍后再试～")
                    }

                }


                var CancelToken = this.$axios.CancelToken;

                let that = this
                this.$axios
                    .get('https://www.17fpv.com/wp-json/jiangqie/v1/part/list',
                    {
                        params:
                        {
                            start: this.current_start,
                            type: this.current_type,
                            name: this.value
                        },
                        cancelToken: new CancelToken(function executor(c)
                        {
                            // 1. cancel函数赋值给cancelRequest属性
                            // 从而可以通过cancelRequest执行取消请求的操作
                            that.cancelRequest = c
                        })
                    })
                    .then(response =>
                    {
                        if (response.data.data < 12)
                        {
                            this.finished = true
                        }
                        this.partsList = this.partsList.concat(response.data.data)
                        this.loading = false

                        this.current_start += 1
                    })
                    .catch(function(error)
                    {

                        if (that.$axios.isCancel(error))
                        {
                            console.log('Request canceled', error.message);
                        }
                        else
                        {
                            console.log(error)
                        }
                    });


            },
            onRefresh()
            {
                // 清空列表数据
                this.finished = false;

                // 重新加载数据
                // 将 loading 设置为 true，表示处于加载状态
                this.loading = true;
                this.onLoad();
            },
            choosePart(id, name, img, part_name)
            {

                for (let i = 0; i < this.choosePartList.length; i++)
                {
                    if (this.choosePartList[i].id == id)
                    {
                        this.$toast('不能选择重复的零件');
                        return false;
                    }
                }

                this.choosePartList.push(
                {
                    id: id,
                    img: img,
                    name: name,
                    part_name: part_name
                })

                this.show = false;
            },
            // position 为关闭时点击的位置
            // instance 为对应的 SwipeCell 实例
            beforeClose(
            {
                name
            })
            {
                this.$dialog.confirm(
                    {
                        title: '',
                        message: '确定要删除零件吗？',
                    })
                    .then(() =>
                    {
                        console.log('删除成功')
                        console.log(name)
                        for (let i = 0; i < this.choosePartList.length; i++)
                        {
                            if (name == this.choosePartList[i].id)
                            {
                                this.choosePartList.splice(i, 1)
                            }
                        }
                        // this.show = false;
                    })
                    .catch(() =>
                    {
                        //     console.log('删除失败')
                        //     this.show = true;
                    });
            },
            openPartListPopup()
            {

                //加载默认数据
                this.$axios
                    .get('https://www.17fpv.com/wp-json/jiangqie/v1/part/alltype')
                    .then(response => (this.partsType = response.data.data.parts_type))
                    .catch(function(error)
                    { // 请求失败处理
                        console.log(error);
                    });
            },
            onChange(index)
            {
              this.activeKey = index

                this.current_type = this.partsType[index].id
                this.current_partName = this.partsType[index].name
                this.current_start = 0

                this.loading = false
                this.finished = false
                this.refreshing = false

                //     清空列表数据
                this.partsList = []

                // 重新加载数据
                // 将 loading 设置为 true，表示处于加载状态
                this.loading = true;
                this.onLoad()

            },
            onInput()
            {

                this.current_start = 0

                this.loading = false
                this.finished = false
                this.refreshing = false

                //     清空列表数据
                this.partsList = []

                // 重新加载数据
                // 将 loading 设置为 true，表示处于加载状态
                this.loading = true;
                this.onLoad()

            },

            strlen(str)
            {
                var len = 0;
                for (var i = 0; i < str.length; i++)
                {
                    var c = str.charCodeAt(i);
                    //单字节加1
                    if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f))
                    {
                        len++;
                    }
                    else
                    {
                        len += 2;
                    }
                }
                return len;
            },
            clickPost()
            {

                if (this.choosePartList.length < 3)
                {
                    this.$toast.fail("至少3个零件")
                    return false;
                }
                if (this.imageList.length < 3)
                {
                    this.$toast.fail("至少3张图片")
                    return false;
                }
                if (this.strlen(this.message) < 15)
                {
                    this.$toast.fail("至少15个字")
                    return false;
                }

                this.toast_post = this.$toast.loading(
                {
                    message: '🚀正在发布...',
                    forbidClick: true,
                    duration: 0
                });

                var formData = new FormData()


                for (let i = 0; i < this.imageList.length; i++)
                {
                    formData.append('photos[]', this.imageList[i].content)
                }

                for (let i = 0; i < this.choosePartList.length; i++)
                {
                    formData.append('parts[]', this.choosePartList[i].id)
                }

                formData.append('content', this.message)
                formData.append('type', 2)

                let that = this

                this.$axios
                    .post('https://www.17fpv.com/wp-json/jiangqie/v1/userpost/post-add', formData)
                    .then(response =>
                    {
                        if (response.data.code == 1)
                        {
                            that.toast_post.clear()
                            that.$toast.fail(response.data.msg)
                        }
                        else
                        {


                          setTimeout(function(){
                            that.toast_post.clear()
                            that.$toast.success(response.data.msg)

                            that.$router.push({
                              path: '/post-success'
                            })
                          },3000)


                        }

                    })
                    .catch(function(error)
                    {
                        console.log(error)
                    });


            },
            clickCancel()
            {
                this.dialog_title = '😭 真的忍心离开吗'
                this.show_dialog = true


            },
            onConfirm () {
              this.$router.push({
                path: '/'
              })
            },
            onCancel () {
              this.show_dialog = false
            },
            afterRead (file) {


              file.status = 'uploading';
              file.message = '上传中...';

              console.log(file)
                lrz(file.file,{quality: 0.3})
                  .then(function (rst) {

                    file.content = rst.base64
                    file.file = rst
                    file.status = '';
                    file.message = '';

                      // 处理成功会执行
                  })
                  .catch(function (err){
                    console.log(err)
                      // 处理失败会执行
                  })
                  .always(function () {
                      // 不管是成功失败，都会执行
                  });


            },
            beforeRead(file) {
              const imageType = [
              'image/png',
              'image/jpeg',
              'image/webp',
              ]
              if(file.type == 'image/gif'){
                this.$toast('不能上传GIF动图');
                return false;
              }
            if (imageType.indexOf(file.type) < 0) {
              this.$toast('请上传图片格式！');
              return false;
            }
            return true;
          }
        },
    }

</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
    .van-sidebar::-webkit-scrollbar
    {
        /*滚动条整体样式*/
        width: 2px;
        /*高宽分别对应横竖滚动条的尺寸*/
        height: 1px;
    }

    .van-sidebar::-webkit-scrollbar-thumb
    {
        /*滚动条里面小方块*/
        border-radius: 10px;
        -webkit-box-shadow: inset 0 0 5px grey;
        background: white;
    }

    .van-sidebar::-webkit-scrollbar-track
    {
        /*滚动条里面轨道*/
        -webkit-box-shadow: inset 0 0 5px white;
        border-radius: 10px;
        background: white;
    }

    .search::-webkit-scrollbar
    {
        /*滚动条整体样式*/
        width: 2px;
        /*高宽分别对应横竖滚动条的尺寸*/
        height: 1px;
    }

    .search::-webkit-scrollbar-thumb
    {
        /*滚动条里面小方块*/
        border-radius: 10px;
        -webkit-box-shadow: inset 0 0 5px grey;
        background: white;
    }

    .search::-webkit-scrollbar-track
    {
        /*滚动条里面轨道*/
        -webkit-box-shadow: inset 0 0 5px white;
        border-radius: 10px;
        background: white;
    }

    .left-box
    {
        width: 25%;
        /* height: 1%; */
        overflow: auto;
        /* position: fixed; */
        left: 0;
        top: 0;
    }

    .right-box
    {
        width: 75%;
        height: 90%;
        overflow: auto;
        position: fixed;
        right: 0;
        top: 0;
    }

    .test
    {
        background-color: red;
        height: 90px;
    }

    .van-sidebar
    {
        width: 100%;
        text-align: center;
        height: 100%;
        position: fixed;
        left: 0;
        /* top: 0; */
        width: 25%;
    }

    .search
    {
        position: fixed;
        right: 0;
        overflow: auto;
        height: 100%;
    }

    .search-bar
    {
        position: fixed;
        /* top: 0; */
        right: 0;
        width: 75%;
        z-index: 2000;
        padding: 12px 7px;
        box-shadow: 10px 0px 10px grey;
    }

    .search-result
    {
        padding-top: 50px;
    }

    .van-sidebar-item
    {
        padding: 15px 2px;
    }

    .van-list
    {
        padding-top: 60px;
    }

    .van-card
    {
        padding: 5px 5px;
        border-bottom: 1px solid #f6f6f6;
        background-color: white;
    }

    .van-card__thum
    {
        width: 70px;
        height: 70px;
    }

    .van-card__content
    {
        min-height: 70px;
    }

    .van-card__desc
    {
        max-height: 60px;
        text-align: left;
    }

    .van-card__thumb
    {
        width: 60px;
        height: 60px;
    }

    .van-card__thumb img
    {
        border-radius: 3px;
    }

    .van-ellipsis
    {
        white-space: break-spaces;
    }

    .goods-card
    {
        margin: 0;
        background-color: @white;
    }

    .delete-button
    {
        height: 100%;
    }

    .van-swipe-cell
    {
        margin-top: 5px;
    }

    .van-tag--danger
    {
        margin-top: 5px;
    }

    .van-uploader
    {
        padding: 15px;
    }

    .van-sidebar-item--select::before
    {
        height: 50px;
    }

    .van-cell__value--alone
    {
        font-size: 16px;
    }

    .van-field
    {
        font-size: 16px;
    }

    .van-dialog
    {
        border-radius: 5px;
    }

</style>
